package core.imust.com.imustcore.fragment.sub;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import core.imust.com.imustcore.R;
import core.imust.com.imustcore.adapter.OneChannelQuickAdapter;
import core.imust.com.imustcore.bean.OneChannelData;
import core.imust.com.imustcore.db.JrttOrmHelper;
import core.imust.com.imustcore.db.NewRecoder;
import core.imust.com.imustcore.net.JrttApi;
import core.imust.com.imustcore.net.OnDataLoadListener;
import core.imust.com.imustcore.net.ResponseData;
import core.imust.com.imustcore.net.RetrofitUtil;
import retrofit2.Call;

/**
 * 1、一个可以下拉，也可以往上拖动的PullToRefreshListView
 *      1.1、将开源控件库的代码引用进来成为一个ModelLib
 *      1.2、依赖 当前app项目，使用这个app去依赖控件库
 *      1.3、在布局文件放一个PullToRefreshListView
 *      1.4、请求网络数据json
 *      1.5、解析
 *      1.6、使用Adapter创建一个Adapter
 *      1.7、将适配器设置给PullToRefreshListView
 */

public class TabChannelFragment extends Fragment implements OnDataLoadListener{
    private String url;//表示该页面获取数据的地址

    public void setUrl(String url) {
        this.url = url;
    }

    private boolean isPull=false;
    private int fangxiang=-1;
    private List<OneChannelData.NewsBean>allList=new ArrayList<>();
    private Handler handler=new Handler();

    private View view;
    private PullToRefreshListView listView;
    private OneChannelData data;
    private OneChannelQuickAdapter adapter;
    //private OneChannelMultiAdapter adapter;

    public TabChannelFragment(){

    }



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initView();
        requestNet();
        return view;
    }

    @Override
    public void initView() {
        view=View.inflate(getContext(),R.layout.fragment_tab_channel,null);
        listView= (PullToRefreshListView) view.findViewById(R.id.list_view);
    }

    @Override
    public void requestNet() {
        JrttApi api= RetrofitUtil.get();
        String requestUrl=url;
        if (fangxiang==11){//取得下一页数据
            requestUrl=data.more;
        }else {
            requestUrl=url;
        }
        String[] args=url.split("\\/");
        Call<ResponseData> call=api.getDataOneChannelNew(args[0],args[1]);//只要去接口中修改
        //调用send方法访问服务端
        RetrofitUtil.send(getContext(),call,TabChannelFragment.this);
    }

    @Override
    public void parsejson(String json) {
        System.out.println(json);
        //解析json
        Gson gson=new Gson();
        data=gson.fromJson(json,OneChannelData.class);
        //如果是进行页面，当时集合没有数据，直接添加到集合中
        if (isPull){
            if (fangxiang==1) {//往下拖
                allList.clear();//清空
                //放入最新的记录
                allList.addAll(data.news);
                //必须让适配器更新一下
            }else {
                //==11往下滚动，说明用户要使用更多的新闻记录来查看，这时不要清空集合，直接加就可以
                //显示的效果是越加越多
                allList.addAll(data.news);
            }
        }else {
            //直接假数据到集合
            allList.addAll(data.news);//将获取服务端数据加到当前集合，以后适配器就显示这个集合的数据
            isPull=true;//后面的操作只能是拖动了
        }

    }

    @Override
    public void showData() {
        /*for (OneChannelData.NewsBean bean :data.news){
            System.out.println(bean.title);
        }*/

        //创建一个Adapter
        adapter=new OneChannelQuickAdapter(getContext(),R.layout.item_new,data.news);
        //只是显示一种行视图的效果，我们现在需要根据type=0 显示 一张图片的视图，type=1显示三张图片的视图
        //OneChannelMultiAdapter adapter=new OneChannelMultiAdapter(getContext(),data.news);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
                //1、将这条新闻的id放到数据库中，表示记录了这条新闻一度
                OneChannelData.NewsBean newsBean=data.news.get(i-1);
                Toast.makeText(getContext(), "id:"+newsBean+" "+newsBean.title, Toast.LENGTH_SHORT).show();
                //改成往数据库中添加一个记录
                JrttOrmHelper helper=new JrttOrmHelper(getContext());
                //获取dao Database Access Object
                Dao<NewRecoder,Integer>dao= null;
                try {
                    dao = helper.getDao(NewRecoder.class);
                    //判断该新闻在数据库没有保存过
                    List<NewRecoder> list=dao.queryForEq("new_id",newsBean.id);//where new_id=1000
                    if (list.size()==0){
                        //不存在，才进行保存
                        NewRecoder recoder=new NewRecoder(newsBean.id+"");
                        dao.create(recoder);//将这条记录插入到数据库新闻中
                        //全部查询
                        adapter.notifyDataSetChanged();//将集合变化这个事情通知ListView
                        fangxiang=-1;
                        /*handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                listView.onRefreshComplete();
                            }
                        });*/
                        /*List<NewRecoder>newRecoders=dao.queryForAll();
                        for (NewRecoder item:newRecoders){
                            System.out.println("已经保存在数据库中的新闻 id"+item.getNewId());
                        }*/
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }

                //2、为你打开一个详情
            }
        });
    }
}
